/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2025-07-05 10:35:43
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2025-07-05 12:06:47
 * @FilePath: /lesson/lesson_net/blog_tcp/TcpClient.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#pragma once

#include <iostream>

#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <unistd.h>
#include <ctime>
#include <cstdarg>
#include <fstream>
#include <cstring>
#include <pthread.h>

class TcpClient
{
public:
    TcpClient(std::string server_ip, int server_port)
        : _sockfd(-1), _server_ip(server_ip), _server_port(server_port)
    {
    }

    void InitClient()
    {
        // 1、创建套接字
        if (_sockfd = socket(AF_INET, SOCK_STREAM, 0) < 0)
        {
            std::cerr << "create sockfd fail" << std::endl;
            exit(-1);
        }
    }

    void Request()
    {
        std::string msg;
        char buffer[1024];
        while (true)
        {
            std::cout << "Please Enter#";
            getline(std::cin, &msg);

            write(_sockfd, msg.c_str(), msg.size());
            ssize_t size = read(_sockfd, buffer, sizeof(buffer) - 1);

            if (size > 0)
            {
                buffer[size] = '\0';
                std::cout << "server echo#" << buffer << std::endl;
            }
            else if (size == 0)
            {
                std::cout << "server close!" << std::endl;
                break;
            }
            else
            {
                std::cerr << " read error!" << std::endl;
                break;
            }
        }
    }

    void Start()
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_addr.s_addr= inet_addr(_server_ip.c_str());
        peer.sin_port = htons(_server_port);

        if (connect(_sockfd, (struct sockaddr *)&peer, sizeof(peer)) == 0)
        {
            std::cout << "connect success ..." << std::endl;
            Request(); // 客户端的请求函数
        }
        else
        {
            // connect error
            std::cerr << "connect failed..." << std::endl;
            exit(-2);
        }
    }
    ~TcpClient()
    {
    }

private:
    int _sockfd;            // 客户端自己的套接字
    std::string _server_ip; // 服务端IP地址
    int _server_port;       // 服务端端口号
};